﻿using ESRI.ArcGIS.Geodatabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PlanningGIS.ArcGIS
{
    /// <summary>
    /// 工作空间对象扩展
    /// </summary>
    public static class WorkspaceExtension
    {
        /// <summary>
        /// 获取工作空间的服务器信息
        /// </summary>
        /// <param name="workspace"></param>
        /// <returns></returns>
        public static string GetPropertyServer(this IWorkspace workspace)
        {
            return GetPropertyValue(workspace, "Server");
        }

        /// <summary>
        /// 获取工作空间实例
        /// </summary>
        /// <param name="workspace"></param>
        /// <returns></returns>
        public static string GetPropertyInstance(this IWorkspace workspace)
        {
            return GetPropertyValue(workspace, "Instance");
        }

        /// <summary>
        /// 获取工作空间用户名称
        /// </summary>
        /// <param name="workspace"></param>
        /// <returns></returns>
        public static string GetPropertyUser(this IWorkspace workspace)
        {
            return GetPropertyValue(workspace, "User");
        }

        /// <summary>
        /// 获取工作空间的连接属性信息，Sde使用Server、其他使用Database
        /// </summary>
        /// <param name="workspace">工作空间</param>
        /// <param name="name">属性名称：Server、Database、Instance、User、Password、Version</param>
        /// <returns></returns>
        public static string GetPropertyValue(this IWorkspace workspace, string name)
        {
            object propertyNames = "";
            object propertyValues = "";
            workspace.ConnectionProperties.GetAllProperties(out propertyNames, out propertyValues);
            System.Array propNameArray = (System.Array)propertyNames;
            System.Array propValuesArray = (System.Array)propertyValues;
            for (int i = 0; i < propNameArray.Length; i++)
            {
                if (propNameArray.GetValue(i).ToString().Equals(name, StringComparison.CurrentCultureIgnoreCase))
                {
                    return propValuesArray.GetValue(i).ToString();
                }
            }
            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workspace"></param>
        /// <returns></returns>
        public static Dictionary<string, dynamic> GetProperties(this IWorkspace workspace)
        {
            Dictionary<string, dynamic> properties = new Dictionary<string, dynamic>();
            object names = "";
            object values = "";
            workspace.ConnectionProperties.GetAllProperties(out names, out values);
            Array nameArr = (Array)names;
            Array valuesArr = (Array)values;
            for (int i = 0; i < nameArr.Length; i++)
            {
                properties.Add(nameArr.GetValue(i).ToString().ToUpper(), valuesArr.GetValue(i));
            }
            return properties;
        }
    }
}
